<template>
  <div id="userManagePage">
    <!-- 搜索表单 -->
    <a-form layout="inline" :model="searchParams" @finish="doSearch" class="search-form">
      <a-form-item label="账号">
        <a-input v-model:value="searchParams.userAccount" placeholder="输入账号" />
      </a-form-item>
      <a-form-item label="用户名">
        <a-input v-model:value="searchParams.userName" placeholder="输入用户名" />
      </a-form-item>
      <a-form-item>
        <a-button type="primary" html-type="submit">搜索</a-button>
      </a-form-item>
      <!-- 新增按钮 -->
      <a-form-item>
        <a-button type="primary" @click="openAddModal">新增</a-button>
      </a-form-item>
    </a-form>

    <!-- 数据表格 -->
    <a-table
      :columns="columns"
      :data-source="dataList"
      :pagination="pagination"
      @change="doTableChange"
      class="user-table"
    >
      <template #bodyCell="{ column, record, index }">
        <template v-if="column.dataIndex === 'serialNumber'">
          {{ (searchParams.current - 1) * searchParams.pageSize + index + 1 }}
        </template>
        <template v-else-if="column.dataIndex === 'userAvatar'">
          <a-image :src="record.userAvatar" :width="45" />
        </template>
        <template v-else-if="column.dataIndex === 'userRole'">
          <a-tag :color="record.userRole === 'admin' ? 'green' : 'blue'">
            {{ record.userRole === 'admin' ? '管理员' : '普通用户' }}
          </a-tag>
        </template>
        <template v-else-if="column.dataIndex === 'createTime'">
          {{ dayjs(record.createTime).format('YYYY-MM-DD HH:mm:ss') }}
        </template>
        <template v-else-if="column.key === 'action'">
          <a-button size="small" @click="openEditModal(record)">编辑</a-button>
          <a-button danger size="small" @click="doDelete(record.id)">删除</a-button>
        </template>
      </template>
    </a-table>

    <!-- 新增用户模态框 -->
    <a-modal
      :visible="addModalVisible"
      title="新增用户"
      okText="确认"
      cancelText="取消"
      @ok="handleAddUser"
      @cancel="closeAddModal"
    >
      <a-form :model="addUserForm" layout="vertical">
        <a-form-item label="账号">
          <a-input v-model:value="addUserForm.userAccount" placeholder="输入账号" />
        </a-form-item>
        <a-form-item label="用户姓名">
          <a-input v-model:value="addUserForm.userName" placeholder="输入用户姓名" />
        </a-form-item>
        <a-form-item label="用户角色">
          <a-select v-model:value="addUserForm.userRole">
            <a-select-option value="user">普通用户</a-select-option>
            <a-select-option value="admin">管理员</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="用户头像">
          <a-input v-model:value="addUserForm.userAvatar" placeholder="输入用户头像链接" />
        </a-form-item>
        <a-form-item label="用户简介">
          <a-input v-model:value="addUserForm.userProfile" placeholder="输入用户简介" />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 编辑用户模态框 -->
    <a-modal
      :visible="editModalVisible"
      title="编辑用户"
      okText="确认"
      cancelText="取消"
      @ok="handleEditUser"
      @cancel="closeEditModal"
    >
      <a-form :model="editUserForm" layout="vertical">
        <a-form-item label="账号">
          <a-input v-model:value="editUserForm.userAccount" placeholder="输入账号" />
        </a-form-item>
        <a-form-item label="用户姓名">
          <a-input v-model:value="editUserForm.userName" placeholder="输入用户姓名" />
        </a-form-item>
        <a-form-item label="用户角色">
          <a-select v-model:value="editUserForm.userRole">
            <a-select-option value="user">普通用户</a-select-option>
            <a-select-option value="admin">管理员</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="用户头像">
          <a-input v-model:value="editUserForm.userAvatar" placeholder="输入用户头像链接" />
        </a-form-item>
        <a-form-item label="用户简介">
          <a-input v-model:value="editUserForm.userProfile" placeholder="输入用户简介" />
        </a-form-item>

      </a-form>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
import { computed, onMounted, reactive, ref } from 'vue'
import {
  addUserUsingPost,
  deleteUserUsingPost,
  listUserVoByPageUsingPost,
  updateUserUsingPost,
} from '@/api/userController'
import { message } from 'ant-design-vue'
import dayjs from 'dayjs'

// 定义列
const columns = [
  {
    title: '序号',
    dataIndex: 'serialNumber',
    key: 'serialNumber',
  },
  {
    title: '账号',
    dataIndex: 'userAccount',
  },
  {
    title: '用户名',
    dataIndex: 'userName',
  },
  {
    title: '头像',
    dataIndex: 'userAvatar',
  },
  {
    title: '用户角色',
    dataIndex: 'userRole',
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
  },
  {
    title: '操作',
    key: 'action',
  },
]

// 数据源
const dataList = ref([])
const total = ref(0)

// 搜索条件
const searchParams = reactive({
  current: 1,
  pageSize: 10,
  sortField: 'createTime',
})

// 新增用户模态框相关
const addModalVisible = ref(false)
const addUserForm = reactive({
  userAccount: '',
  userName: '',
  userRole: 'user',
  userAvatar: '',
  userProfile:'',
})

// 编辑用户模态框相关
const editModalVisible = ref(false)
const editUserForm = reactive({
  id: '',
  userAccount: '',
  userName: '',
  userRole: 'user',
  userAvatar: '',
  userProfile:'',
})

// 表格变化处理
const doTableChange = (page: any) => {
  searchParams.current = page.current
  searchParams.pageSize = page.pageSize
  fetchData()
}

// 分页参数
const pagination = computed(() => ({
  current: searchParams.current ?? 1,
  pageSize: searchParams.pageSize ?? 10,
  total: total.value,
  showSizeChanger: true,
  showTotal: (total) => `共 ${total} 条`,
}))

// 获取数据
const fetchData = async () => {
  const res = await listUserVoByPageUsingPost({ ...searchParams })
  if (res.data.data) {
    dataList.value = res.data.data.records ?? []
    total.value = res.data.data.total ?? 0
  } else {
    message.error('获取用户数据失败')
  }
}

// 执行搜索
const doSearch = () => {
  searchParams.current = 1
  fetchData()
}

// 删除数据
const doDelete = async (id: string) => {
  if (!id) return
  const res = await deleteUserUsingPost({ id })
  if (res.data.code === 0) {
    message.success('删除成功')
    fetchData()
  } else {
    message.error('删除失败')
  }
}

// 打开新增用户模态框
const openAddModal = () => {
  addModalVisible.value = true
  // 每次打开新增模态框时清空表单数据
  addUserForm.username = ''
  addUserForm.name = ''
  addUserForm.userRole = 'user'
  addUserForm.userAvatar = ''
  addUserForm.email = ''
  addUserForm.phone = ''
}

// 关闭新增用户模态框
const closeAddModal = () => {
  addModalVisible.value = false
}

// 处理新增用户
const handleAddUser = async () => {
  const res = await addUserUsingPost({ ...addUserForm })
  if (res.data.code === 0) {
    message.success('新增用户成功')
    closeAddModal()
    fetchData()
  } else {
    message.error('新增用户失败')
  }
}

// 打开编辑用户模态框
const openEditModal = (record: any) => {
  editModalVisible.value = true
  editUserForm.id = record.id
  editUserForm.username = record.username
  editUserForm.name = record.name
  editUserForm.userRole = record.userRole
  editUserForm.userAvatar = record.userAvatar
  editUserForm.email = record.email
  editUserForm.phone = record.phone
}

// 关闭编辑用户模态框
const closeEditModal = () => {
  editModalVisible.value = false
}

// 处理编辑用户
const handleEditUser = async () => {
  const res = await updateUserUsingPost({ ...editUserForm })
  if (res.data.code === 0) {
    message.success('编辑用户成功')
    closeEditModal()
    fetchData()
  } else {
    message.error('编辑用户失败')
  }
}

onMounted(() => {
  fetchData()
})
</script>

<style scoped>
#userManagePage {
}

.search-form {
  margin-bottom: 10px;
  display: flex;
}

.user-table {
  margin-top: 10px;
}

.pagination {
  margin-top: 10px;
  text-align: center;
}

/* 减少表单项的间距 */
#userManagePage :deep(.ant-form-item) {
  margin-bottom: 8px;
}

/* 减少表格单元格的内边距 */
.ant-table-tbody > tr > td {
  padding: 8px;
}

/* 减少分页组件的内边距 */
#userManagePage :deep(.ant-pagination-options) {
  padding: 4px;
}
</style>
